package com.hjrpc.babyyamall.authserver.exception;

import com.hjrpc.common.exception.BizCodeEnum;
import com.hjrpc.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice(basePackages = "com.hjrpc.babyyamall.authserver.web")
public class AuthServerExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handlerArgumentValidException(MethodArgumentNotValidException e) {

        return R.error(BizCodeEnum.VALID_EXCEPTION).put("data", e.getBindingResult().getFieldErrors().stream()
                .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage, (v1, v2) -> v1 + "," + v2)));
    }

    @ExceptionHandler(value = Throwable.class)
    public R handlerGlobalException(Throwable e) {
        log.error("异常", e);
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION);
    }
}
